<!-- SoftKeyboard.vue -->
<template>
    <div v-if="visible" class="soft-keyboard" @click.stop>
        <!-- 字母键盘 -->
        <div v-show="currentLayout === 'letter'" class="keyboard-layout">
            <div
                class="key-row"
                v-for="(row, rowIndex) in letterKeys"
                :key="rowIndex"
            >
                <button
                    v-for="key in row"
                    :key="key.label"
                    :class="[
                        'key',
                        key.type || '',
                        { active: activeKey === key.label },
                    ]"
                    @mousedown="handleMouseDown(key)"
                    @mouseup="handleMouseUp"
                    @touchstart="handleTouchStart(key)"
                    @touchend="handleTouchEnd"
                    @click="handleClick(key)"
                >
                    {{ key.display || key.label }}
                </button>
            </div>

            <div class="key-row special-keys">
                <button
                    class="key shift"
                    :class="{ active: isShiftActive }"
                    @click="toggleShift"
                >
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                        <path
                            d="M12 5V19M5 12L12 5L19 12"
                            stroke="currentColor"
                            stroke-width="2"
                            stroke-linecap="round"
                            stroke-linejoin="round"
                        />
                    </svg>
                </button>
                <button class="key layout-switch" @click="switchToSymbol">
                    123
                </button>
                <button class="key space" @click="inputChar(' ')">空格</button>
                <button class="key layout-switch" @click="switchToChinese">
                    中
                </button>
                <button
                    class="key backspace"
                    @mousedown="startBackspace"
                    @mouseup="stopBackspace"
                    @touchstart="startBackspace"
                    @touchend="stopBackspace"
                >
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                        <path
                            d="M3 6H21M19 6V20C19 20.5304 18.7893 21.0391 18.4142 21.4142C18.0391 21.7893 17.5304 22 17 22H7C6.46957 22 5.96086 21.7893 5.58579 21.4142C5.21071 21.0391 5 20.5304 5 20V6M8 6V4C8 3.46957 8.21071 2.96086 8.58579 2.58579C8.96086 2.21071 9.46957 2 10 2H14C14.5304 2 15.0391 2.21071 15.4142 2.58579C15.7893 2.96086 16 3.46957 16 4V6"
                            stroke="currentColor"
                            stroke-width="2"
                            stroke-linecap="round"
                            stroke-linejoin="round"
                        />
                    </svg>
                </button>
            </div>
        </div>

        <!-- 符号键盘 -->
        <div v-show="currentLayout === 'symbol'" class="keyboard-layout">
            <div
                class="key-row"
                v-for="(row, rowIndex) in symbolKeys"
                :key="rowIndex"
            >
                <button
                    v-for="key in row"
                    :key="key.label"
                    :class="['key', key.type || '']"
                    @click="handleSymbolClick(key)"
                >
                    {{ key.display || key.label }}
                </button>
            </div>

            <div class="key-row special-keys">
                <button class="key layout-switch" @click="switchToLetter">
                    ABC
                </button>
                <button class="key space" @click="inputChar(' ')">空格</button>
                <button class="key layout-switch" @click="switchToChinese">
                    中
                </button>
                <button
                    class="key backspace"
                    @mousedown="startBackspace"
                    @mouseup="stopBackspace"
                    @touchstart="startBackspace"
                    @touchend="stopBackspace"
                >
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                        <path
                            d="M3 6H21M19 6V20C19 20.5304 18.7893 21.0391 18.4142 21.4142C18.0391 21.7893 17.5304 22 17 22H7C6.46957 22 5.96086 21.7893 5.58579 21.4142C5.21071 21.0391 5 20.5304 5 20V6M8 6V4C8 3.46957 8.21071 2.96086 8.58579 2.58579C8.96086 2.21071 9.46957 2 10 2H14C14.5304 2 15.0391 2.21071 15.4142 2.58579C15.7893 2.96086 16 3.46957 16 4V6"
                            stroke="currentColor"
                            stroke-width="2"
                            stroke-linecap="round"
                            stroke-linejoin="round"
                        />
                    </svg>
                </button>
            </div>
        </div>

        <!-- 中文键盘 -->
        <div
            v-show="currentLayout === 'chinese'"
            class="keyboard-layout chinese-layout"
        >
            <!-- 拼音显示区域 -->
            <div class="pinyin-display" v-if="pinyinInput">
                <span class="pinyin-text">{{ pinyinInput }}</span>
                <button class="clear-pinyin" @click="clearPinyin">×</button>
            </div>

            <!-- 候选词区域 -->
            <div v-if="candidates.length > 0" class="candidates-area">
                <button
                    v-for="(candidate, index) in candidates"
                    :key="index"
                    class="candidate-item"
                    @click="selectCandidate(candidate)"
                >
                    {{ index + 1 }}. {{ candidate }}
                </button>
            </div>

            <!-- 中文键盘布局 -->
            <div
                class="key-row"
                v-for="(row, rowIndex) in chineseKeys"
                :key="rowIndex"
            >
                <button
                    v-for="key in row"
                    :key="key.label"
                    :class="['key', key.type || '']"
                    @click="handleChineseClick(key)"
                >
                    {{ key.display || key.label }}
                </button>
            </div>

            <div class="key-row special-keys">
                <button
                    class="key shift"
                    :class="{ active: isShiftActive }"
                    @click="toggleShift"
                >
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                        <path
                            d="M12 5V19M5 12L12 5L19 12"
                            stroke="currentColor"
                            stroke-width="2"
                            stroke-linecap="round"
                            stroke-linejoin="round"
                        />
                    </svg>
                </button>
                <button class="key layout-switch" @click="switchToLetter">
                    ABC
                </button>
                <button class="key space" @click="inputPinyinSpace">
                    空格
                </button>
                <button class="key layout-switch" @click="switchToSymbol">
                    123
                </button>
                <button
                    class="key backspace"
                    @mousedown="startBackspace"
                    @mouseup="stopBackspace"
                    @touchstart="startBackspace"
                    @touchend="stopBackspace"
                >
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                        <path
                            d="M3 6H21M19 6V20C19 20.5304 18.7893 21.0391 18.4142 21.4142C18.0391 21.7893 17.5304 22 17 22H7C6.46957 22 5.96086 21.7893 5.58579 21.4142C5.21071 21.0391 5 20.5304 5 20V6M8 6V4C8 3.46957 8.21071 2.96086 8.58579 2.58579C8.96086 2.21071 9.46957 2 10 2H14C14.5304 2 15.0391 2.21071 15.4142 2.58579C15.7893 2.96086 16 3.46957 16 4V6"
                            stroke="currentColor"
                            stroke-width="2"
                            stroke-linecap="round"
                            stroke-linejoin="round"
                        />
                    </svg>
                </button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, watch, onUnmounted } from 'vue';

// 定义props
const props = defineProps({
    visible: {
        type: Boolean,
        default: false,
    },
    targetElement: {
        type: Object,
        default: null,
    },
});

// 定义emit事件
const emit = defineEmits(['update:visible', 'input']);

// 键盘状态
const currentLayout = ref('letter');
const isShiftActive = ref(false);
const activeKey = ref('');
const backspaceInterval = ref(null);

// 中文输入相关
const pinyinInput = ref('');
const candidates = ref([]);

// 字母键盘布局
const letterKeysBase = [
    [
        { label: 'q' },
        { label: 'w' },
        { label: 'e' },
        { label: 'r' },
        { label: 't' },
        { label: 'y' },
        { label: 'u' },
        { label: 'i' },
        { label: 'o' },
        { label: 'p' },
    ],
    [
        { label: 'a' },
        { label: 's' },
        { label: 'd' },
        { label: 'f' },
        { label: 'g' },
        { label: 'h' },
        { label: 'j' },
        { label: 'k' },
        { label: 'l' },
    ],
    [
        { label: 'z' },
        { label: 'x' },
        { label: 'c' },
        { label: 'v' },
        { label: 'b' },
        { label: 'n' },
        { label: 'm' },
    ],
];

// 符号键盘布局
const symbolKeys = ref([
    [
        { label: '1' },
        { label: '2' },
        { label: '3' },
        { label: '4' },
        { label: '5' },
        { label: '6' },
        { label: '7' },
        { label: '8' },
        { label: '9' },
        { label: '0' },
    ],
    [
        { label: '-' },
        { label: '/' },
        { label: ':' },
        { label: ';' },
        { label: '(' },
        { label: ')' },
        { label: '$' },
        { label: '&' },
        { label: '@' },
        { label: '"' },
    ],
    [
        { label: '.' },
        { label: ',' },
        { label: '?' },
        { label: '!' },
        { label: "'" },
        { label: '+' },
        { label: '=' },
        { label: '_' },
        { label: '#' },
    ],
]);

// 中文键盘布局
const chineseKeys = [
    [
        { label: 'q' },
        { label: 'w' },
        { label: 'e' },
        { label: 'r' },
        { label: 't' },
        { label: 'y' },
        { label: 'u' },
        { label: 'i' },
        { label: 'o' },
        { label: 'p' },
    ],
    [
        { label: 'a' },
        { label: 's' },
        { label: 'd' },
        { label: 'f' },
        { label: 'g' },
        { label: 'h' },
        { label: 'j' },
        { label: 'k' },
        { label: 'l' },
    ],
    [
        { label: 'z' },
        { label: 'x' },
        { label: 'c' },
        { label: 'v' },
        { label: 'b' },
        { label: 'n' },
        { label: 'm' },
    ],
];

// 计算属性：根据shift状态调整字母键盘
const letterKeys = computed(() => {
    if (!isShiftActive.value) return letterKeysBase;

    return letterKeysBase.map((row) =>
        row.map((key) => ({
            ...key,
            label: key.label.toUpperCase(),
            display: key.label.toUpperCase(),
        }))
    );
});

// 切换键盘布局
const switchToLetter = () => {
    currentLayout.value = 'letter';
};

const switchToSymbol = () => {
    currentLayout.value = 'symbol';
};

const switchToChinese = () => {
    currentLayout.value = 'chinese';
    clearPinyin();
};

// 输入字符
const inputChar = (char) => {
    emit('input', char);
    if (props.targetElement) {
        const element = props.targetElement;
        const start = element.selectionStart || 0;
        const end = element.selectionEnd || 0;
        const value = element.value || '';

        element.value = value.substring(0, start) + char + value.substring(end);
        element.setSelectionRange(start + 1, start + 1);
        element.focus();
    }
};

// 处理字母按键点击
const handleClick = (key) => {
    inputChar(key.label);
    if (isShiftActive.value && key.label.match(/[a-z]/)) {
        toggleShift();
    }
};

// 处理符号按键点击
const handleSymbolClick = (key) => {
    inputChar(key.label);
};

// 处理中文按键点击
const handleChineseClick = (key) => {
    // 添加拼音字符
    pinyinInput.value += key.label;
    updateCandidates();
};

// 更新候选词
const updateCandidates = () => {
    if (!pinyinInput.value) {
        candidates.value = [];
        return;
    }

    // 简化的拼音匹配逻辑（实际应用中应使用更完整的字典）
    const mockDict = {
        ni: ['你', '妮', '泥', '拟'],
        nin: ['您', '恁'],
        ning: ['宁', '拧', '凝'],
        wo: ['我', '窝', '蜗', '喔'],
        ta: ['他', '她', '它', '踏'],
        zhong: ['中', '钟', '忠', '终'],
        wen: ['文', '问', '温', '闻'],
    };

    // 简单匹配逻辑
    const matched = [];
    for (const [pinyin, words] of Object.entries(mockDict)) {
        if (pinyin.startsWith(pinyinInput.value.toLowerCase())) {
            matched.push(...words);
        }
    }

    candidates.value = [...new Set(matched)].slice(0, 8);
};

// 选择候选词
const selectCandidate = (word) => {
    inputChar(word);
    clearPinyin();
};

// 清除拼音输入
const clearPinyin = () => {
    pinyinInput.value = '';
    candidates.value = [];
};

// 输入拼音空格
const inputPinyinSpace = () => {
    if (candidates.value.length > 0) {
        selectCandidate(candidates.value[0]);
    } else if (pinyinInput.value) {
        inputChar(pinyinInput.value);
        clearPinyin();
    } else {
        inputChar(' ');
    }
};

// Shift键切换
const toggleShift = () => {
    isShiftActive.value = !isShiftActive.value;
};

// 退格功能
const startBackspace = () => {
    performBackspace();
    backspaceInterval.value = setInterval(performBackspace, 150);
};

const stopBackspace = () => {
    if (backspaceInterval.value) {
        clearInterval(backspaceInterval.value);
        backspaceInterval.value = null;
    }
};

const performBackspace = () => {
    if (currentLayout.value === 'chinese' && pinyinInput.value) {
        pinyinInput.value = pinyinInput.value.slice(0, -1);
        updateCandidates();
    } else {
        emit('input', 'BACKSPACE');
        if (props.targetElement) {
            const element = props.targetElement;
            const start = element.selectionStart || 0;
            const end = element.selectionEnd || 0;
            const value = element.value || '';

            if (start === end && start > 0) {
                element.value =
                    value.substring(0, start - 1) + value.substring(end);
                element.setSelectionRange(start - 1, start - 1);
            } else {
                element.value =
                    value.substring(0, start) + value.substring(end);
                element.setSelectionRange(start, start);
            }
            element.focus();
        }
    }
};

// 鼠标/触摸事件处理
const handleMouseDown = (key) => {
    activeKey.value = key.label;
};

const handleMouseUp = () => {
    activeKey.value = '';
};

const handleTouchStart = (key) => {
    activeKey.value = key.label;
};

const handleTouchEnd = () => {
    activeKey.value = '';
};

// 监听可见性变化
watch(
    () => props.visible,
    (newVal) => {
        if (!newVal) {
            clearPinyin();
            isShiftActive.value = false;
        }
    }
);

// 点击外部关闭键盘
const handleClickOutside = (event) => {
    if (props.visible) {
        emit('update:visible', false);
    }
};

// 组件挂载时添加全局点击监听
document.addEventListener('click', handleClickOutside);

// 组件卸载时移除监听
onUnmounted(() => {
    document.removeEventListener('click', handleClickOutside);
    if (backspaceInterval.value) {
        clearInterval(backspaceInterval.value);
    }
});
</script>

<style scoped>
.soft-keyboard {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: #f5f5f5;
    border-top: 1px solid #ddd;
    padding: 10px;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
    z-index: 1000;
    user-select: none;
}

.keyboard-layout {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.key-row {
    display: flex;
    justify-content: center;
    gap: 6px;
}

.key {
    flex: 1;
    min-width: 0;
    height: 45px;
    border: none;
    border-radius: 8px;
    background: white;
    color: #333;
    font-size: 18px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    transition: all 0.1s ease;
    padding: 0;
}

.key:hover {
    background: #f0f0f0;
}

.key.active {
    background: #007aff;
    color: white;
    transform: scale(0.95);
}

.key.space {
    flex: 3;
}

.key.backspace,
.key.shift,
.key.layout-switch {
    background: #e0e0e0;
    color: #333;
}

.key.backspace:hover,
.key.shift:hover,
.key.layout-switch:hover {
    background: #d0d0d0;
}

.key.shift.active {
    background: #007aff;
    color: white;
}

.chinese-layout .pinyin-display {
    background: white;
    border-radius: 8px;
    padding: 10px 15px;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pinyin-text {
    font-size: 20px;
    color: #007aff;
    font-weight: bold;
}

.clear-pinyin {
    background: none;
    border: none;
    font-size: 24px;
    cursor: pointer;
    color: #999;
}

.candidates-area {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-bottom: 10px;
}

.candidate-item {
    flex: 1;
    min-width: 0;
    height: 40px;
    background: white;
    border: 1px solid #ddd;
    border-radius: 8px;
    font-size: 16px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
}

.candidate-item:hover {
    background: #f0f0f0;
}

@media (max-width: 768px) {
    .key {
        height: 40px;
        font-size: 16px;
    }

    .key-row {
        gap: 4px;
    }

    .soft-keyboard {
        padding: 8px;
    }
}
</style>
